package com.xiaot.shopping.product.service.impl;

import com.baomidou.mybatisplus.core.conditions.update.UpdateWrapper;
import com.baomidou.mybatisplus.extension.service.impl.ServiceImpl;
import com.baomidou.mybatisplus.extension.toolkit.SqlHelper;
import com.xiaot.shopping.product.dao.CategoryBrandRelationDao;
import com.xiaot.shopping.product.dao.CategoryDao;
import com.xiaot.shopping.product.entity.CategoryBrandRelationEntity;
import com.xiaot.shopping.product.entity.CategoryEntity;
import com.xiaot.shopping.product.service.CategoryService;
import org.springframework.stereotype.Service;
import org.springframework.transaction.annotation.Transactional;

import javax.annotation.Resource;
import java.util.Comparator;
import java.util.List;
import java.util.stream.Collectors;


@Service("categoryService")
public class CategoryServiceImpl extends ServiceImpl<CategoryDao, CategoryEntity> implements CategoryService {

    @Resource
    private CategoryBrandRelationDao categoryBrandRelationDao;

    @Override
    public List<CategoryEntity> listWithTree() {
        List<CategoryEntity> entities = baseMapper.selectList(null);
        return getChildren(null, entities);
    }

    private List<CategoryEntity> getChildren(CategoryEntity entity, List<CategoryEntity> entities) {
        return entities.stream()
                .filter(f -> entity == null ? f.getParentCid() == 0 : f.getParentCid().equals(entity.getCatId()))
                .peek(p -> p.setChildren(getChildren(p, entities)))
                .sorted(Comparator.comparingInt(CategoryEntity::getSort))
                .collect(Collectors.toList());
    }

    @Override
    public void removeMenuByIds(List<Long> asList) {
        // todo 检查当前删除的菜单是否被别的地方引用
        baseMapper.deleteBatchIds(asList);
    }

    @Override
    @Transactional
    public boolean updateByIdAnyWhere(CategoryEntity category) {
        CategoryBrandRelationEntity entity = new CategoryBrandRelationEntity();
        entity.setCatelogName(category.getName());
        categoryBrandRelationDao.update(entity, new UpdateWrapper<CategoryBrandRelationEntity>().eq("catelog_id", category.getCatId()));
        return SqlHelper.retBool(getBaseMapper().updateById(category));
    }
}